<template>
  <div class="address-management">
    <!-- 新增地址按钮 -->
    <div class="header">
      <el-button type="primary" @click="handleOpenDialog('add')">新增地址</el-button>
    </div>

    <!-- 地址列表 -->
    <div class="address-list">
      <div v-if="loading" class="loading-container">
        <el-skeleton :rows="3" animated />
      </div>
      
      <template v-else>
        <div v-for="(item, index) in addressList" :key="item.addrID" class="address-item">
          <div class="info">
            <div class="name">
              {{ item.phone }}
              <el-tag v-if="item.status" type="success" size="small" style="margin-left: 8px">默认</el-tag>
            </div>
            <div class="detail">{{ item.address }}</div>
          </div>
          <div class="actions">
            <el-button link @click="handleOpenDialog('edit', item)">编辑</el-button>
            <el-button link type="danger" @click="handleDelete(item.addrID)">删除</el-button>
          </div>
        </div>
        
        <div v-if="addressList.length === 0" class="empty-address">
          <el-empty description="暂无地址" />
        </div>
      </template>
    </div>

    <!-- 地址编辑弹窗 -->
    <el-dialog
        v-model="dialogVisible"
        :title="operationType === 'add' ? '新增地址' : '编辑地址'"
        width="600px"
    >
      <el-form
          ref="formRef"
          :model="formData"
          :rules="rules"
          label-width="80px"
      >
        <el-form-item label="电话" prop="phone">
          <el-input v-model="formData.phone" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input
              v-model="formData.address"
              type="textarea"
              placeholder="请输入详细地址"
          />
        </el-form-item>
        <el-form-item label="默认地址">
          <el-switch v-model="formData.status" />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { AddressApi } from '@/api/new/userAddrApi.ts';
import UserUtil from '@/utils/User/User.js';

// 地址列表数据
const addressList = ref([]);
const loading = ref(false);

// 弹窗相关状态
const dialogVisible = ref(false);
const operationType = ref('add'); // add/edit
const formRef = ref(null);

// 表单数据
const formData = reactive({
  addrID: null,
  userID: null,
  address: '',
  phone: '',
  status: false
});

// 验证规则
const rules = reactive({
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' }
  ],
  address: [{ required: true, message: '请输入详细地址', trigger: 'blur' }]
});

// 获取地址列表
const fetchAddressList = async () => {
  if (!UserUtil.isLogin()) {
    ElMessage.warning('请先登录');
    return;
  }
  
  try {
    loading.value = true;
    const userID = UserUtil.getUserId();
    const response = await AddressApi.getAddressList(userID);
    addressList.value = response || [];
  } catch (error) {
    console.error('获取地址列表失败:', error);
    ElMessage.error(`获取地址列表失败: ${error.message || '未知错误'}`);
  } finally {
    loading.value = false;
  }
};

// 打开弹窗
const handleOpenDialog = (type, row) => {
  operationType.value = type;
  
  // 重置表单
  Object.keys(formData).forEach(key => {
    formData[key] = key === 'status' ? false : '';
  });
  
  // 设置用户ID
  formData.userID = UserUtil.getUserId();
  
  if (type === 'edit' && row) {
    // 编辑模式，填充表单数据
    Object.keys(formData).forEach(key => {
      if (key in row) {
        formData[key] = row[key];
      }
    });
  }
  
  dialogVisible.value = true;
};

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return;
  
  try {
    await formRef.value.validate();
    
    if (operationType.value === 'add') {
      // 新增地址
      await AddressApi.addAddress({
        userID: formData.userID,
        address: formData.address,
        phone: formData.phone,
        status: formData.status
      });
      ElMessage.success('添加地址成功');
    } else {
      // 更新地址
      await AddressApi.updateAddress({
        addrID: formData.addrID,
        userID: formData.userID,
        address: formData.address,
        phone: formData.phone,
        status: formData.status
      });
      ElMessage.success('更新地址成功');
    }
    
    // 刷新地址列表
    fetchAddressList();
    // 关闭弹窗
    dialogVisible.value = false;
  } catch (error) {
    if (error.message) {
      ElMessage.error(`操作失败: ${error.message}`);
    } else {
      console.log('表单验证失败');
    }
  }
};

// 删除地址
const handleDelete = (addrID) => {
  ElMessageBox.confirm('确定删除该地址吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await AddressApi.deleteAddress(addrID);
      ElMessage.success('删除地址成功');
      // 刷新地址列表
      fetchAddressList();
    } catch (error) {
      ElMessage.error(`删除失败: ${error.message || '未知错误'}`);
    }
  }).catch(() => {
    // 取消删除，不做任何操作
  });
};

// 页面加载时获取地址列表
onMounted(() => {
  fetchAddressList();
});
</script>

<style lang="less" scoped>
.address-management {
  padding: 20px;

  .header {
    margin-bottom: 20px;
  }

  .loading-container {
    padding: 20px 0;
  }

  .empty-address {
    padding: 40px 0;
    text-align: center;
  }

  .address-list {
    .address-item {
      padding: 15px;
      margin-bottom: 10px;
      border: 1px solid #eee;
      border-radius: 4px;
      display: flex;
      justify-content: space-between;
      align-items: center;
      transition: all 0.3s;

      &:hover {
        box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
      }

      .info {
        flex: 1;
        .name {
          font-size: 16px;
          margin-bottom: 8px;
          display: flex;
          align-items: center;
        }
        .detail {
          color: #666;
        }
      }

      .actions {
        margin-left: 20px;
        :deep(.el-button) {
          margin-left: 10px;
        }
      }
    }
  }
}
</style>